package eerbaar.expression.internal.lib;

import eerbaar.context.IContext;
import eerbaar.context.IParams;
import eerbaar.context.ParamFactory;
import eerbaar.game.IGame;
import eerbaar.memory.IMemory;
import eerbaar.persona.IPersona;
import eerbaar.shared.tree.INode;

public class FindProgramExpression extends AbstractExpression {

    private static final String[] paramNames = new String[] { "text" };

    private String text;

    private IParams params;

    public FindProgramExpression() {
        super("findProgram");
        this.params = ParamFactory.createParams();
    }

    public FindProgramExpression(IParams params) {
        super("findProgram");
        this.params = params;

        setup(params);
    }

    @Override
    public boolean execute(IContext model) {

        boolean found = match(model);
        return found;
    }

    @Override
    public String[] getParamNames() {

        return paramNames;
    }

    @Override
    public IParams getParams() {

        return this.params;
    }

    private boolean match(IContext model) {

        boolean found = false;

        IGame game = (IGame) model;
        IPersona pet = game.getPersona("pet");
        IMemory memory = pet.getHead().getBrain().getMemory();
        INode programNode = memory.getIdeaNode();
        INode[] programs = programNode.getChildren();
        for (INode node : programs) {
            String program = node.getPayload().getValue();
            int index = program.indexOf(text);
            if (index > -1) {
                found = true;
                break;
            }
        }

        return found;
    }

    @Override
    public void setParams(IParams params) {
        this.params = params;
        setup(params);
    }

    private void setup(IParams params) {

        this.text = params.get("text");
    }
}
